package logging

import (
	"Hypnos-Soundcore/constants"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"time"
)

var (
	logToFile         bool
	logWriter         io.WriteCloser
	apiWriter         io.WriteCloser
	commerceWriter    io.WriteCloser
	appTrackingWriter io.WriteCloser
)

// SetWriter .
func SetWriter(ltf bool, lw, aw, cw, atw io.WriteCloser) {
	logToFile = ltf
	logWriter = lw
	apiWriter = aw
	commerceWriter = cw
	appTrackingWriter = atw
}

// GetServerInfo .
func GetServerInfo(RequestID string) (server Server) {
	conf := GetLoggingTool().GetConfig()
	server = Server{
		Hostname:  conf.HostName,
		Area:      conf.Area,
		RequestID: RequestID,
	}
	return
}

func saveLog(log *DeviceLogging) error {
	bytes, err := json.Marshal(log)
	if err != nil {
		return err
	}
	if logWriter != nil {
		if logToFile {
			_, err = logWriter.Write(append(bytes, '\n'))
		} else {
			msg := []byte(fmt.Sprintf("%s:%s\n", "logging", string(bytes)))
			_, err = logWriter.Write(msg)
		}
	}
	return err
}

// SaveLogEventToFile 写日志到logging文件，数据是json格式，会抓到es保存
func SaveLogEventToFile(eventName string, param map[string]interface{}, err error) error {
	if err != nil {
		param[constants.ParamMessage] = err.Error()
	}
	serverEvent := &ServerEventsRequest{Events: []ServerEventsData{ServerEventsData{Name: eventName, Params: param}}}
	_, saveErr := SaveServerEventsToFile(serverEvent)
	return saveErr
}

// SaveServerEventsToFile 服务端事件写日志
func SaveServerEventsToFile(req *ServerEventsRequest) (ret int64, err error) {
	if !Enable() {
		err = errors.New(" Logging has been Disabled ")
		return
	}

	for _, row := range req.Events {
		log := DeviceLogging{
			Type:      constants.LabelServerEvent,
			TimeStamp: time.Now().UTC().Format(time.RFC3339),
			Server:    GetServerInfo(""),
			Device: Device{
				Model:      constants.EnvName(),
				AppName:    constants.ServerName(),
				AppVersion: constants.ServerVersion(),
			},
			ServerEvent: &row,
		}
		if err = saveLog(&log); err != nil {
			return 0, err
		}
	}
	return
}
